//
//  LEUserInfoCoreDataManager.m
//  qqqqqq
//
//  Created by iOSer on 2017/3/21.
//  Copyright © 2017年 iOSer. All rights reserved.
//

#import "LEUserInfoCoreDataManager.h"
#import "LEUserInfo+CoreDataClass.h"
#import "LEUserInfoModel.h"
#import "LECommodity.h"
@interface LEUserInfoCoreDataManager()<NSFetchedResultsControllerDelegate>

@end
@implementation LEUserInfoCoreDataManager

static LEUserInfoCoreDataManager *manager = nil;
+(instancetype)shareInstance{
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        manager = [[LEUserInfoCoreDataManager alloc] init];
    });
    return manager;
}



-(void)saveContext:(LEUserInfoModel *)userinfoModel{
    // 建立获取数据的请求对象，并指明操作的实体为Employee
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"LEUserInfo"];
    
    // 执行获取请求，获取到符合要求的托管对象
    NSError *error = nil;
    NSArray <LEUserInfo *> *userInfos = [self.manageObjectContext executeFetchRequest:request error:&error];
    if (userInfos.count!=0) {
        [userInfos enumerateObjectsUsingBlock:^(LEUserInfo * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            obj.moneyNum = (int32_t)userinfoModel.moneyNum;
            obj.weekNum = (int32_t)userinfoModel.weekNum;
            obj.aliPayNum = (int32_t)userinfoModel.aliPayNum;
            obj.reputationNum = (int32_t)userinfoModel.reputationNum;
            obj.healthNum = (int32_t)userinfoModel.healthNum;
            obj.userComModelArray = userinfoModel.userComModelArray;
            obj.ownComModelArray = userinfoModel.ownComModelArray;
        }];
    }else{
        LEUserInfo *userInfo = [NSEntityDescription insertNewObjectForEntityForName:@"LEUserInfo" inManagedObjectContext:self.manageObjectContext];
        userInfo.moneyNum = (int32_t)userinfoModel.moneyNum;
        userInfo.weekNum = (int32_t)userinfoModel.weekNum;
        userInfo.aliPayNum = (int32_t)userinfoModel.aliPayNum;
        userInfo.reputationNum = (int32_t)userinfoModel.reputationNum;
        userInfo.healthNum = (int32_t)userinfoModel.healthNum;
        userInfo.userComModelArray = userinfoModel.userComModelArray;
        userInfo.ownComModelArray = userinfoModel.ownComModelArray;
    }
    if (self.manageObjectContext.hasChanges) {
        [self.manageObjectContext save:&error];
    }
    // 错误处理
    if (error) {
        NSLog(@"CoreData Update Data Error : %@", error);
    }
    
}
-(void)readContextWithtargetCallBack:(void (^)(LEUserInfoModel *userInfoModel))targetCallBack withDefeatedBlock:(void (^)())defeatedBlock{
    // 创建请求对象，并指明操作User表
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"LEUserInfo"];
    
    // 创建NSFetchedResultsController控制器实例，并绑定MOC
    NSError *error = nil;
    
    NSArray <LEUserInfo *> *userInfos = [self.manageObjectContext executeFetchRequest:request error:&error];
    // 错误处理
    if (error) {
        NSLog(@"CoreData Ergodic Data Error : %@", error);
    }
    if (userInfos.count!=0) {
        LEUserInfo *userInfo = userInfos.lastObject;
        
        LEUserInfoModel *infoModel = [LEUserInfoModel new];
        infoModel.moneyNum = userInfo.moneyNum;
        infoModel.aliPayNum = userInfo.aliPayNum;
        infoModel.weekNum = userInfo.weekNum;
        infoModel.healthNum = userInfo.healthNum;
        infoModel.reputationNum = userInfo.reputationNum;
        infoModel.userComModelArray = (NSMutableArray *)userInfo.userComModelArray;
        [infoModel.userComModelArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            LECommodity *aa= obj;
            NSLog(@"%@",aa.isRefresh==YES?@"YESSSSSSS":@"NOOOOOOO");
        }];
        infoModel.ownComModelArray = (NSMutableArray *)userInfo.ownComModelArray;
        targetCallBack(infoModel);
        return;
    }else{
        defeatedBlock();
    }
    
    
}

-(NSManagedObjectContext *)manageObjectContext{
    if (!_manageObjectContext) {
        _manageObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
        _manageObjectContext.persistentStoreCoordinator = self.persistentStoreCoordinator;
    }
    return _manageObjectContext;
}
-(NSManagedObjectModel *)managedObjectModel{
    if (!_managedObjectModel) {
        NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"LEGameProgress" withExtension:@"momd"];
        _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    }
    return _managedObjectModel;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator{
    NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                             [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
                             [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
    NSString *dataPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
    NSURL *fileURL  = [NSURL fileURLWithPath:[dataPath stringByAppendingFormat:@"/LEUserInfo.sqlite"]];
    if (!_persistentStoreCoordinator) {
        //实例化 - 指定管理对象模型
        _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:self.managedObjectModel];
            NSError *error = nil;
        //添加存储器
        //Type:存储类型, 数据库/XML/二进制/内存
        //configuration:不需要额外配置,可以为nil
        //URL:数据保存的文件的URL
        //options:可以为空
        if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:fileURL options:options error:&error]) {
                    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
                    dict[NSLocalizedDescriptionKey] = @"未能初始化应用程序的保存数据";
                    dict[NSUnderlyingErrorKey] = error;
                    error = [NSError errorWithDomain:@"错误码" code:9999 userInfo:dict];
            
                    NSLog(@"报错信息 %@, %@", error, [error userInfo]);
                    abort();
                }

    }

    return _persistentStoreCoordinator;
    
}
@end
